package imoney.server;

import javax.servlet.ServletContext;

import imoney.client.rpc.GreetingService;
import imoney.shared.CookieBuilderShared;
import imoney.shared.exception.NoSuchPersonException;
import imoney.shared.exception.PositionOutOfDateException;
import imoney.shared.model.Person;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService { 

	/**
	 * Returns the pseudo of the person
	 * @throws PositionOutOfDateException when the person is already logged to 
	 * app but cookie is out of date. 
	 * @throws NoSuchPersonException when the person is not in the context.
	 */
	public String greetServer(String cookieValue) throws NoSuchPersonException, PositionOutOfDateException {
		escapeHtml(cookieValue); // Even if the data comes from a cookie, just in case.
		ServletContext context = getServletContext();
		int position = CookieBuilderShared.readPosition(cookieValue);
		String googleID = CookieBuilderShared.readUserId(cookieValue);
		Person person = UserServlet.getPerson(position, googleID, context);
		return person.getPseudo();
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}
}
